<template>
	<view class="page" :style="'background-image: url('+indexBg+');'">
    <u-navbar :fixed="false" title="发起签署" placeholder bgColor="transparent"></u-navbar>
    <view class="search-box">
      <view class="search-title">合同名称</view>
      <u--input :customStyle="{background: '#fff'}" placeholder="请输入" v-model="contractName" />
    </view>
    <template v-if="contractUrl==''">
      <view class="contract-name">
        <view class="">合同模板名称</view>
        <u-search borderColor="#dadbde" v-model="searchVal" searchIconColor="#3ec1ba" :inputStyle="{borderRadius: '16rpx'}" shape="square"
          bgColor="#fff" height="76rpx" placeholder="请输入" :showAction="false" @search="search" @clear="search" />
      </view>
      <view class="tabs-type">
        <view class="tabs-type-item" :class="{active: templateType=='平台模板'}" @click="templateType='平台模板';selectId='';">平台模板</view>
        <view class="tabs-type-item" :class="{active: templateType=='公司模板'}" @click="templateType='公司模板';selectId='';">公司模板</view>
      </view>
      <u-radio-group placement="row" v-model="selectId" @change="selectIdChange">
        <view class="list">
          <view class="list-item" v-for="item in templateList" :key="item.templateUrl">
            <image v-if="templateType=='平台模板'" src="https://gowork365.com/prod-api/profile/mini/company/contract1.png" />
            <image v-if="templateType=='公司模板'" src="https://gowork365.com/prod-api/profile/mini/company/contract2.png" />
            <view class="u-flex-1">
              <view class="name u-line-2">{{ item.templateName }}</view>
              <view class="time">{{ item.createTime }}</view>
            </view>
            <u-radio :name="item.templateUrl" shape="circle" activeColor="#388b87" />
          </view>
        </view>
      </u-radio-group>
      <view v-if="templateList.length == 0" class="a-empty"><a-empty></a-empty></view>
      <view class="footer-primary-btn-actions">
        <view class="footer-primary-l-btn" @click="jumpTo('/other/staff/template')">合同模板管理</view>
        <view class="footer-primary-r-btn" @click="contractUrl=selectId">确认选择</view>
      </view>
    </template>
    <template v-else>
      <view class="form-file-content">
        <view class="title">已选择文件</view>
        <view class="file" @click="handleForm">
          <u-icon name="eye" color="#138E88" size="24rpx"></u-icon>
          <view class="u-flex-1 u-line-1">{{ fileName }}</view>
        </view>
        <view class="title">签署对象</view>
        <view class="investor-list">
          <view class="investor-item" v-for="(item, index) in checkedList" :key="item.id">
            <view class="investor-name">
              <image src="https://gowork365.com/prod-api/profile/mini/company/investor.png" />
              <text class="u-line-1">{{ item.staffName }}</text>
            </view>
            <view class="investor-actions" @click="delSelectItem(index)">
              <text>删除</text>
              <u-icon name="close" color="rgba(0,0,0,0.5)" size="24rpx"></u-icon>
            </view>
          </view>
        </view>
        <view class="footer-primary-btn-actions">
          <view class="footer-primary-l-btn" @click="jumpTo('/other/staff/staffSelect', {type: '1'})">选择签署对象</view>
          <view class="footer-primary-r-btn" @click="submitForm">确定</view>
        </view>
      </view>
    </template>
    <u-popup :show="!initiationMethod" @close="goBack()" :closeOnClickOverlay="false" closeable>
      <view class="popup-box">
        <view class="popup-title">选择发起方式</view>
        <view class="initiationMethod">
          <view class="initiationMethod-item" @click="setInitiationMethod('导入本地文件')">
            <image src="https://gowork365.com/prod-api/profile/mini/company/initiationMethod1.png" />
            <view>导入微信文件</view>
          </view>
          <view class="initiationMethod-item" @click="setInitiationMethod('选择合同模板')">
            <image src="https://gowork365.com/prod-api/profile/mini/company/initiationMethod2.png" />
            <view>选择合同模板</view>
          </view>
        </view>
        <view class="tips">支持扩展名：.doc .docx .pdf</view>
      </view>
		</u-popup>
    <u-popup :show="openFormFie">
      <view class="popup-box">
        <view class="popup-title">签署合同<text class="u-m-l-12" style="color: #2979ff;" @click="handleForm">查看合同</text></view>
        <view class="popup-form">
          <scroll-view scroll-y class="scroll">
            <view class="form-info form-info-no-style">
              <view class="form-box">
                <view class="form-item" v-for="(item, index) in formFields" :key="index">
                  <view class="form-lable required">{{ item.formName }}</view>
                  <view class="form-content">
                    <u--input @input="fieldsInput($event, index)" :type="item.formType" placeholder="请输入" border="none" inputAlign="right" v-model="item.formValue" />
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="save-primary-btn-actions">
          <view class="save-primary-l-btn" @click="contractUrl=''">重新选择合同</view>
          <view class="save-primary-r-btn" @click="saveFormFields">保存</view>
        </view>
      </view>
		</u-popup>
	</view>
</template>

<script>
import { listGsTemplateList, listPtTemplateList, addSign, getTemplateUrl } from '@/api/index'
import { uploadFile } from '@/common/util'

export default {
  data() {
    return {
      indexBg: 'https://gowork365.com/prod-api/profile/mini/index/indexBg1.png',
      initiationMethod: '',
      searchVal: '',
      selectId: '',
      checkedList: [],
      templateType: '',
      templateList: [],
      contractName: '',
      contractUrl: '',
      fileUrl: '',
      fileName: '',
      formFields: [],
      openFormFie: false,
      pickerType: '',
      formPickerColumns: [],
      dateTimeType: '',
      dateTimeValue: '',
    }
  },
  watch: {
    templateType() {
      this.search()
    },
    contractUrl(n) {
      if(n) {
        const info = this.templateList.find(v => v.templateUrl == n)
        this.formFields = []
        this.openFormFie = false
        return
        if(info && info.components && info.components.length) {
          this.formFields = info.components.filter(v => v.componentType != 'FILL_IMAGE' && v.componentType != 'ATTACHMENT').map(v => {
            return {
              formId: v.componentRecipientId,
              formName: v.componentName,
              formType: v.componentType,
              formExtra: v.componentExtra,
              formValue: v.componentValue || '',
            }
          })
          this.openFormFie = true
        } else {
          this.formFields = []
          this.openFormFie = false
        }
      } else {
        this.formFields = []
        this.openFormFie = false
      }
    },
  },
  onShow() {
  },
  methods: {
    confirmDateTime(e) {
      const dateStr = formatTimeTwo(e.value, 'Y-M-D')
      this.fieldsInput(dateStr, this.dateTimeType)
      this.dateTimeType = ''
    },
    showDateTime(item, index) {
      this.dateTimeValue = new Date()
      this.dateTimeType = index
    },
    confirmPicker(e) {
      const packerStr = e.value[0]
      this.fieldsInput(packerStr, this.pickerType)
      this.pickerType = ''
    },
    showPicker(item, index) {
      const formExtra = JSON.parse(item.formExtra)
      this.formPickerColumns = formExtra.Values
      this.pickerType = index
    },
    fieldsInput(v, index) {
      const info = this.formFields[index]
      info.formValue = v
      this.$set(this.formFields, index, info)
    },
    saveFormFields() {
      let flag = false
      this.formFields.forEach(v => {
        if(v.formValue === '') {
          flag = true
        }
      })
      if(flag) {
        uni.showToast({
          icon: 'none',
          title: '请完善签署信息!',
        })
        return
      }
      this.openFormFie = false
    },
    handleForm() {
      if(this.templateType=='公司模板') {
        // const url = this.baseUrl + this.contractUrl
        // downloadFile(url, true)
        getTemplateUrl({ contractUrl: this.contractUrl }).then(response => {
          const previewUrl = response.data.templates[0].previewUrl
          uni.setStorageSync('url', previewUrl)
          this.jumpTo('/pages/webView/webView')
        })
      } else {
        getTemplateUrl({ contractUrl: this.contractUrl }).then(response => {
          const previewUrl = response.data.templates[0].previewUrl
          uni.setStorageSync('url', previewUrl)
          this.jumpTo('/pages/webView/webView')
        })
      }
    },
    submitForm() {
      const that = this
      if(!this.checkedList.length) {
        uni.showToast({
          icon: 'none',
          title: '请选择签署对象!',
        })
        return
      }
      if(!this.contractName) {
        uni.showToast({
          icon: 'none',
          title: '请输入合同名称',
        })
        return
      }
      const parameter = {
        contractName: this.contractName,
        initiationMethod: this.initiationMethod,
        templateType: this.templateType,
        contractUrl: this.contractUrl,
        userIds: this.checkedList.map(v => v.id).join(','),
        contractType: '员工关系',
      }
      uni.showLoading({ mask: true })
      parameter.from = 'APP'
      parameter.formFields = this.formFields.map(v => {
        return {
          componentName: v.formName,
          componentValue: v.formValue,
        }
      })
      addSign(parameter).then(response => {
        uni.hideLoading()
        if(response.code == 200) {
          uni.showToast({
            icon: 'none',
            title: '签署成功',
          })
          setTimeout(() => {
            that.goBack()
          }, 1000)
        } else {
          uni.showToast({
            icon: 'none',
            title:  response.msg,
          })
        }
      });
      // if(this.initiationMethod=='选择合同模板' && this.templateType == '平台模板') {
      //   parameter.formFields = this.formFields.map(v => {
      //     return {
      //       componentName: v.formName,
      //       componentValue: v.formValue,
      //     }
      //   })
      //   addSign(parameter).then(response => {
      //     uni.hideLoading()
      //     if(response.code == 200) {
      //       uni.showToast({
      //         icon: 'none',
      //         title: '签署成功',
      //       })
      //       setTimeout(() => {
      //         that.goBack()
      //       }, 1000)
      //     } else {
      //       uni.showToast({
      //         icon: 'none',
      //         title:  response.msg,
      //       })
      //     }
      //   });
      // } else {
      //   addSign(parameter).then(response => {
      //     uni.showToast({
      //       icon: 'none',
      //       title: '新增成功',
      //     })
      //     setTimeout(() => {
      //       that.goBack()
      //     }, 1000)
      // });
      // }
    },
    delSelectItem(index) {
      this.checkedList.splice(index, 1)
    },
    /** 查询合同模板管理列表 */
    getTemplateList() {
      uni.showLoading({ mask: true })
      if(this.templateType=='公司模板') {
        // listGsTemplateList({templateName: this.searchVal, templateType: '员工关系'}).then(response => {
        //   uni.hideLoading()
        //   this.templateList = response.data;
        // });
        uni.showLoading({ mask: true })
        listPtTemplateList({
          templateName: this.searchVal,
          userFlowTypeId: this.baseAppId=='wxa023b292fd19d41d'?'yDtIXUU2wpi5fkUuJ2FuPvVksmdkur0a':'yDtBSUUckpxyb0pnUkNgc6qRnRtVe9ZZ',
          systemType: '公司'
        }).then(response => {
          uni.hideLoading()
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.templateUrl = t.templateId
            t.templateName = t.templateName
          })
        });
      } else {
        uni.showLoading({ mask: true })
        listPtTemplateList({
          templateName: this.searchVal,
          userFlowTypeId: this.baseAppId=='wxa023b292fd19d41d'?'yDtIXUU2wpi5fkUuJ2FuPvVksmdkur0a':'yDtBSUUckpxyb0pnUkNgc6qRnRtVe9ZZ',
          systemType: '平台'
        }).then(response => {
          uni.hideLoading()
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.templateUrl = t.templateId
            t.templateName = t.templateName
          })
        });
      }
    },
    async setInitiationMethod(type) {
      this.initiationMethod = type
      if(type == '导入本地文件') {
        uni.showToast({
          icon: 'none',
          title: '请在电脑端上传本地文件',
        })
        this.initiationMethod = ''
        return
        const file = await uploadFile()
        if(file.code != 200) {
          this.initiationMethod = ''
          return
        }
        this.contractUrl = file.fileName
        this.fileName = file.newFileName
      } else {
        this.templateType = '平台模板'
      }
    },
    search() {
      this.templateList = []
      this.getTemplateList()
    },
    selectIdChange(e) {
      const index = this.templateList.findIndex(v => v.templateUrl == e)
      this.fileName = this.templateList[index].templateName
    },
  }
}
</script>

<style lang="scss" scoped>
.page{
	width: 750rpx;
	min-height: 100vh;
  background: #F4F7F6;
  position: relative;
  background-repeat: no-repeat;
  background-size: 750rpx 348rpx;
  padding-bottom: 180rpx;
  .search-box {
    width: 686rpx;
    margin: 48rpx auto;
    display: flex;
    align-items: center;
    gap: 16rpx;
    .search-title {
      font-family: PingFangSC, PingFang SC;
      font-size: 24rpx;
      color: #FFFFFF;
    }
  }
  .contract-name {
    width: 750rpx;
    height: 140rpx;
    background: #FFFFFF;
    padding: 32rpx;
    display: flex;
    align-items: center;
    gap: 16rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: rgba(0,0,0,0.85);
    margin-bottom: 32rpx;
  }
  .tabs-type {
    width: 686rpx;
    margin: 0 auto 32rpx;
    display: flex;
    gap: 32rpx;
    .tabs-type-item {
      width: 196rpx;
      height: 76rpx;
      line-height: 76rpx;
      text-align: center;
      background: #FFFFFF;
      border-radius: 38rpx;
      font-family: PingFangSC, PingFang SC;
      font-size: 24rpx;
      color: #138E88;
      border: 2rpx solid #fff;
    }
    .active {
      background: #E9F8F6;
      border: 2rpx solid #138E88;
    }
  }
  .list {
    margin: 0 auto;
    .list-item {
      width: 686rpx;
      margin-bottom: 32rpx;
      background: #FFFFFF;
      box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(11,102,97,0.2);
      border-radius: 16rpx;
      padding: 48rpx 32rpx;
      display: flex;
      gap: 24rpx;
      image {
        width: 104rpx;
        height: 104rpx;
        flex-shrink: 0;
      }
      .name {
        font-size: 28rpx;
        color: rgba(0,0,0,0.85);
        margin-bottom: 16rpx;
      }
      .time {
        font-size: 24rpx;
        color: rgba(0,0,0,0.25);
      }
    }
  }
  .form-file-content {
    margin: 80rpx auto;
    width: 686rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(11,102,97,0.2);
    border-radius: 16rpx;
    padding: 32rpx;
    .title {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: rgba(0,0,0,0.85);
      margin-bottom: 30rpx;
    }
    .file {
      width: 100%;
      padding: 0 60rpx;
      height: 76rpx;
      background: #E9F8F6;
      border-radius: 8rpx;
      font-family: PingFangSC, PingFang SC;
      font-size: 24rpx;
      color: #138E88;
      margin-bottom: 30rpx;
      display: flex;
      align-items: center;
      gap: 12rpx;
    }
    .investor-list {
      .investor-item {
        padding-bottom: 30rpx;
        border-bottom: 2rpx dashed #EDF3F1;
        margin-bottom: 30rpx;
        display: flex;
        justify-content: space-between;
        gap: 20rpx;
        .investor-name {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 8rpx;
          font-family: PingFangSC, PingFang SC;
          font-size: 24rpx;
          color: rgba(0,0,0,0.85);
          image {
            width: 32rpx;
            height: 32rpx;
            flex-shrink: 0;
          }
        }
        .investor-actions {
          display: flex;
          align-items: center;
          gap: 8rpx;
          font-family: PingFangSC, PingFang SC;
          font-size: 24rpx;
          color: rgba(0,0,0,0.5);
        }
      }
    }
  }
}
.popup-box {
  .popup-title {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 28rpx;
    margin-bottom: 48rpx;
  }
  .initiationMethod {
    display: flex;
    justify-content: center;
    gap: 30rpx;
    margin-bottom: 48rpx;
    .initiationMethod-item {
      width: 312rpx;
      height: 196rpx;
      background: rgba(25,185,246,0.15);
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 22rpx;
      font-family: PingFangSC, PingFang SC;
      font-size: 24rpx;
      color: rgba(0,0,0,0.85);
      image {
        width: 88rpx;
        height: 72rpx;
      }
    }
  }
  .tips {
    text-align: center;
    font-family: PingFangSC, PingFang SC;
    font-size: 24rpx;
    color: rgba(0,0,0,0.85);
    margin-bottom: 120rpx;
  }
}
</style>
